| 12345678910111213141516171819202122232425262728293031323334 |
- import { useEffect, useRef } from 'react';
- import { isClient } from '@growi/core/dist/utils';
- import { useRouter } from 'next/router';
- import type { Props } from '../general-page/types';
- /**
- * Custom hook for syncing pathname by Shallow Routing
- * Optimized to minimize unnecessary router operations and re-renders
- */
- export const useShallowRouting = (props: Props): void => {
- const router = useRouter();
- const lastPathnameRef = useRef<string>();
- // Sync pathname by Shallow Routing with performance optimization
- useEffect(() => {
- if (!isClient() || !props.currentPathname) return;
- // Skip if pathname hasn't changed (prevents unnecessary operations)
- if (lastPathnameRef.current === props.currentPathname) return;
- const currentURL = decodeURI(window.location.pathname);
- // Only update if URLs actually differ
- if (currentURL !== props.currentPathname) {
- const { search, hash } = window.location;
- router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
- }
- // Update reference for next comparison
- lastPathnameRef.current = props.currentPathname;
- }, [props.currentPathname, router]);
- };
|